/**
 * Created by Jack on 2015/8/18.
 */
var async = require('async');
var AV = require('leanengine');

//操作产品的模型信息
var Homepage = AV.Object.extend("Homepage");
var Classify = AV.Object.extend("Classify");
var User = AV.Object.extend("_User");
var JuicePackage = AV.Object.extend("JuicePackage");
var Product = AV.Object.extend("Product");

module.exports = {
    getHomepage:function(){
        var query = new AV.Query(Homepage);
        query.equalTo('status',"1");
        query.equalTo('channel',"2")
        query.descending('cName');
        query.ascending('ordnum');
        return query.find();
    },
    getHomeClassify:function(classifyArr){
        var query = new AV.Query(Classify);
        query.containedIn('gjz',classifyArr);
        query.ascending('orderno');
        return query.find();
    },

    dayMark:function(userid){
        if(userid){
            var query = new AV.Query(User);
            query.equalTo('objectId',userid);
            return query.first();
        } else{
            //throw 'userid should not be empty!';
            return new AV.Promise.error("userid should not be empty!");
        }
    },


    /**
     * 加入套餐
     * @param uid
     * @param pid
     * @param count
     */
    addIntoPackage:function(uid,pid,psid,count){
        var promise = new AV.Promise();
        if(!uid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!pid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!psid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!count){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        async.auto({
            //判断套餐内是否有该规格的商品
            isInPackage:function(callback)
            {
                var query = new AV.Query(JuicePackage);
                query.equalTo('uid', uid+"");
                query.equalTo('pid', pid+"");
                query.equalTo('psid', psid+"");
                query.first().then(function (res) {
                    var status = 0;
                    if (res) {
                        status = 1;
                    }
                    callback(null, {info: res, status: status});
                }).catch(function (err) {
                    callback({code: 1000, msg: err});
                });
            } ,
            getProductInfo:function (callback,results) {
                //根据pid和psid获取商品价格
                var query = new AV.Query(Product);
                query.get(pid).then(function (res) {
                    var spec = res.get('spec');
                    var price = spec[psid]['grprice'];          //原价
                    var packagePrice = spec[psid]['price'];        //套餐价
                    callback(null, {price:price,packagePrice:packagePrice});
                }).catch(function (err) {
                    callback({code: 1000, msg: err});
                });
            },
            updateJuicePackage:['isInPackage','getProductInfo',function(callback,results){
                //status == 1 表示updatePackage，status==0 表示添加新商品
                if (parseInt(results.isInPackage.status) === 1) {
                    //存在，则更新数量
                    var query = new AV.Query(JuicePackage);
                    query.get(results.isInPackage.info.id).then(function(res){
                        res.set('uid', uid);
                        res.set('pid', pid);
                        res.set('psid', psid);
                        res.set('price',results.getProductInfo.price+'');
                        res.set('packagePrice',results.getProductInfo.packagePrice+'');
                        //console.log(parseInt(res.get('count')));
                        res.set('count', parseInt(count)+parseInt(res.get('count')));
                        res.save().then(function(){
                            callback(null, {code:0,msg:'update juice package success'});
                        }).catch(function(err){
                            callback(err);
                        });
                    }).catch(function(err){
                        callback(err);
                    });
                } else {
                    //不存在相同商品，则添加。添加前需要先获取到商品的原价和活动价
                    var updatePro = new JuicePackage();
                    updatePro.set('uid', uid+'');
                    updatePro.set('pid', pid+'');
                    updatePro.set('psid', psid+'');
                    updatePro.set('price',results.getProductInfo.price+'');
                    updatePro.set('packagePrice',results.getProductInfo.packagePrice+'');
                    updatePro.set('count', parseInt(count));
                    updatePro.save().then(function(){
                        callback(null, {code:0,msg:'add juice package success'});
                    }).catch(function(err){
                        callback(err);
                    });
                }
            }],
        },function(err,results){
            if(err){
                //console.log(err);
                promise.reject(err);
            }else{
                //console.log(results.updateJuicePackage);
                promise.resolve(results.updateJuicePackage);
            }
        });
        return promise;
    },
    /**
     * 获取当前用户的套餐记录
     * @param uid 用户ID
     * @returns {*} 用户套餐数据
     */
    showMyPackage:function(uid){
        if(uid){
            var query = new AV.Query(JuicePackage);
            query.equalTo('uid',uid);
            return query.find();
        }else{
            return new AV.Promise.error("uid should not be empty!");
        }
    },

    /**
     * isPackage  :是否加入套餐    ，Pruduct
     * classify   :判断分类是否为下午茶  ，Pruduct
     */
    showPackage:function(){
        var query = new AV.Query(Product);
        //query.equalTo('gjz','grxwctc');
        query.equalTo('cid',21);
        query.equalTo('status',1);
        return query.find();
    },
    deleteFromPackage:function(uid,pid,psid){
        var promise = new AV.Promise();
        //console.log(11111111111);
        if(!uid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!pid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        if(!psid){
            return new AV.Promise.error({code:150});        //产品编号不能为空
        }
        async.waterfall([
            function(callback){
                var query = new AV.Query(JuicePackage);
                query.equalTo('uid',uid);
                query.equalTo('pid',pid);
                query.equalTo('psid',psid);
                query.first().then(function(res){
                    callback(null, res);
                })
            },
            function(isHasPro,callback){
                if(isHasPro){
                    isHasPro.destroy().then(function(res){
                        callback(null, {code:0});
                    }).catch(function(err){
                        callback({code:1});
                    })
                }else{
                    callback(null, {code:0});
                }
            }
        ],function(err,result){
            if(err){
                //console.log("err");
                promise.reject(err);
            }else{
                //console.log("success");
                promise.resolve(result);
            }
        });
        return promise;
    }
};
